package com.asimplefox.service.impl;

import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.entity.Invite;
import com.asimplefox.entity.User;
import com.asimplefox.entity.vo.InviteOut;
import com.asimplefox.mapper.InviteMapper;
import com.asimplefox.service.IInviteService;
import com.asimplefox.service.IUserService;
import com.asimplefox.service.abst.ServiceImplAll;
import io.github.kloping.judge.Judge;
import io.github.kloping.rand.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kloping
 * @since 2024-10-25
 */
@Service
public class InviteServiceImpl extends ServiceImplAll<InviteMapper, Invite> implements IInviteService {

    @Autowired
    IUserService userService;

    @Override
    public Object all(UserRoleDetails details) {
        Invite invite = this.lambdaQuery().eq(Invite::getUserId, details.getUser().getId()).one();
        if (invite == null) {
            invite = new Invite();
            invite.setPcode(getAnyCodee());
            invite.setUserId(details.getUser().getId());
            this.save(invite);
        }
        InviteOut inviteOut = new InviteOut();
        inviteOut.setCode(invite.getPcode());
        inviteOut.setUserId(details.getUser().getId());

        if (Judge.isNotEmpty(invite.getBcode())) {
            Invite fi = this.lambdaQuery().eq(Invite::getPcode, invite.getBcode()).one();
            User fuser = userService.getById(fi.getUserId());
            fuser.setPwd("").setTelephone("").setEmail("");
            inviteOut.setFuser(fuser);
        }

        List<Invite> invites = this.lambdaQuery().eq(Invite::getBcode, invite.getPcode()).list();
        List<User> susers = new ArrayList<>();
        for (Invite i : invites) {
            User suser = userService.getById(i.getUserId());
            suser.setPwd("").setTelephone("").setEmail("");
            susers.add(suser);
        }
        inviteOut.setSusers(susers);
        return inviteOut;
    }

    private char[] ALL = {
            '1', '2', '3', '4', '5',
            '1', '2', '3', '4', '5',
            '6', '7', '8', '9', '0',
            '6', '7', '8', '9', '0',
            'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    public String getAnyCodee() {
        char[] end = new char[6];
        for (int i = 0; i < 6; i++) {
            end[i] = ALL[RandomUtils.RANDOM.nextInt(ALL.length)];
        }
        String pcode = new String(end);
        if (this.lambdaQuery().eq(Invite::getPcode, pcode).one() != null) {
            return getAnyCodee();
        }
        return pcode;
    }
}
